package com.m4f.city.business.security;

import java.util.ArrayList;
import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.m4f.city.business.domain.InternalUser;
import com.m4f.city.business.service.ifc.IServiceLocator;
import com.m4f.gaeweb.business.service.impl.GaeM4FUserDetailService;
import com.m4f.gaeweb.model.GaeM4FUser;

public class InternalUserDetailService extends GaeM4FUserDetailService {
	private static final Logger LOGGER = Logger.getLogger(InternalUserDetailService.class.getName());
	public static final String ROLE_USER = "ROLE_USER";
	public static final String ROLE_MANAGER = "ROLE_MANAGER"; // This role is for users with flag admin enabled. Represents the users who are admin into the organization.
	
	@Autowired
	protected IServiceLocator serviceLocator;
	
	public InternalUserDetailService(String rootUser, String rootPassword) {
		super(rootUser, rootPassword);
	}

	@Override
	public GaeM4FUser loadGaeM4FUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		try {
			InternalUser user = this.serviceLocator.getUserService().getUser(username);
			if(user != null) {
				Authentication authenticationContext = SecurityContextHolder.getContext().getAuthentication();
				// Depending on the admin flag into the user model, the user will have ROLE_MANAGER or ROLE_USER
				ArrayList<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
				if(user.getAdmin())	authorities.add(new GrantedAuthorityImpl(ROLE_MANAGER));
				else authorities.add(new GrantedAuthorityImpl(ROLE_USER));
				user.setAuthorities(authorities);
			} else {
				throw new UsernameNotFoundException("User not found: " + username);
			}
			return user;
		} catch(Exception e) {
			throw new UsernameNotFoundException("User not found: " + username);
		}
	}

	@Override
	public GaeM4FUser createRootUser() {
		InternalUser root = new InternalUser();
		root.setEmail(this.rootUserName);
		root.setPassword(this.rootEncodedPassword);
		
		return root;
	}
}